package com.wq.spit.service;

import com.wq.common.util.IdWorker;
import com.wq.spit.dao.SpitDao;
import com.wq.spit.entity.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询所有
    public List<Spit> findAll(){
        return spitDao.findAll();
    }
    //根据id查询
    public Spit findById(String id){
        return spitDao.findById(id).get();
    }
    //新增
    public void insert(Spit spit){
        spit.set_id(idWorker.nextId()+"");
        spit.setPublishtime(new Date());
        spit.setShare(1);
        spit.setThumbup(1);
        spit.setVisits(1);
        spit.setState("1");
        spitDao.insert(spit);
    }
    //修改
    public void update(Spit spit){
        spitDao.save(spit);
    }
    //删除
    public void delectById(String id){
        spitDao.deleteById(id);
    }

    public Page<Spit>findByParentid(String parentid,int page,int size){
        PageRequest request=PageRequest.of(page-1, size);
        return spitDao.findByParentid(parentid,request);
    }
    //点赞+1
    public void Thumbup(String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        mongoTemplate.updateFirst(query, update, Spit.class);
    }
    //吐槽+1
    public void visits(String id){
        Spit spit = new Spit();
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("visits", 1);
        mongoTemplate.updateFirst(query, update, Spit.class);
    }



}
